package com.lh.web.controller;

import com.lh.common.utils.Result;
import com.lh.web.config.PayPalConfig;
import com.lh.web.form.PaymentFrom;
import com.paypal.api.payments.*;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author FH
 * @ClassName: PaymentController
 * @Description: (类作用)
 * @date: 2020-05-20 15:05
 */
@Api(value="PaymentController",tags={"支付"})
@RestController
@RequestMapping("payment")
@Slf4j
public class PaymentController {

    @Autowired
    PayPalConfig payPalConfig;

    // 回调地址
    private static Integer orderId = null;
    private static String SUCCESS_URL = "https://www.baidu.com";
    private static String FAIL_URL = "http://www.163.com";
    private static String CANCEL_URL = "https://www.autohome.com.cn/shenzhen/?pvareaid=1001299";

    @RequestMapping(method = RequestMethod.POST, value = "/payment")
    public String payment(HttpServletRequest request, @RequestParam("paymentId") String paymentId, @RequestParam("PayerID") String payerId) throws PayPalRESTException {

        // 设置付款人详细信息
        Payer payer = new Payer();
        payer.setPaymentMethod("paypal");

        // Set redirect URLs
        RedirectUrls redirectUrls = new RedirectUrls();
        redirectUrls.setCancelUrl("http://localhost:3000/cancel");
        redirectUrls.setReturnUrl("http://localhost:3000/process");

        // 付款明细
        Details details = new Details();
        details.setShipping("1");
        details.setSubtotal("5");
        details.setTax("1");

        // 付款金额
        Amount amount = new Amount();
        amount.setCurrency("USD");
        // 总计必须等于运费、税金和小计之和
        amount.setTotal("7");
        amount.setDetails(details);

        // 交易信息
        Transaction transaction = new Transaction();
        transaction.setAmount(amount);
        transaction.setDescription("This is the payment transaction description.");

        // 将事务添加到列表
        List<Transaction> transactions = new ArrayList<Transaction>();
        transactions.add(transaction);

        // 添加付款详细信息
        Payment payment = new Payment();
        payment.setIntent("sale");
        payment.setPayer(payer);
        payment.setRedirectUrls(redirectUrls);
        payment.setTransactions(transactions);

        APIContext apiContext = new APIContext(payPalConfig.getClientId(), payPalConfig.getClientSecret(),"sandbox");
        payment.setId(paymentId);
        PaymentExecution paymentExecute = new PaymentExecution();
        paymentExecute.setPayerId(payerId);
        payment.execute(apiContext, paymentExecute);

        // Create payment
        try {
            Payment createdPayment = payment.create(apiContext);

            Iterator links = createdPayment.getLinks().iterator();
            while (links.hasNext()) {
                Links link = (Links) links.next();
                if (link.getRel().equalsIgnoreCase("approval_url")) {
                    // Redirect the customer to link.getHref()
                }
            }
        } catch (PayPalRESTException e) {
            System.err.println(e.getDetails());
        }
        return"";
    }

    /**
     * 查询商品管理
     */
    @ApiOperation(value = "退款")
    @GetMapping("/getRefundRequest")
    //    @RequiresPermissions("shop:getShopList")
    public Result getRefundRequest() {
        Map<String, Object> params = new HashMap<String, Object>();
        APIContext apiContext = new APIContext(payPalConfig.getClientId(), payPalConfig.getClientSecret(), payPalConfig.getMode());
        RefundRequest refund = new RefundRequest();
        Amount amount = new Amount();
        amount.setCurrency("USD");
        amount.setTotal("1");
        refund.setAmount(amount);
        refund.setReason("测试");
        try {
            Sale sale = new Sale();
            sale.setId("9MB0667584354054M");
            DetailedRefund res = sale.refund(apiContext, refund);
            //注意这段代码，获取saleId
           /* Payment payment = Payment.get(apiContext, "1TB406078F726293B");
            Transaction transaction = payment.getTransactions().get(0);
            RelatedResources resources = transaction.getRelatedResources().get(0);
            String id = resources.getSale().getId();*/

            // ### Api Context
            // Pass in a `ApiContext` object to authenticate
            // the call and to send a unique request id
            // (that ensures idempotency). The SDK generates
            // a request id if you do not pass one explicitly.

            // Refund by posting to the APIService
            // using a valid AccessToken

        } catch (PayPalRESTException e) {
            throw new IllegalStateException("failed to refund saleId=" , e);
        }
        return Result.ok();
    }
}
